package No1_100.No1_10.AddTwoNumbers_2;
//Definition for singly-linked list.


public class Solution {
	public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode ret = l1;
		ListNode l3 = l1;
		
		if (l1 == null) {
			return l2;
		}
		if (l2 == null) {
			return l1;
		}
		int flag = 0;
		while((l1 != null)&&(l2 != null)){
			int sum = l1.val + l2.val + flag;
			if (sum>=10) {
				sum = sum - 10;
				flag = 1;
			}
			else {
				flag = 0;
			}
			l1.val = sum;
			l3 = l1;
			l1 = l1.next;
			l2 = l2.next;
		}
		l1 = (l2 != null)?l3:l1;
		while (l2 != null) {
			int sum = l2.val + flag;
			if (sum>=10) {
				sum = sum - 10;
				flag = 1;
			}
			else {
				flag = 0;
			}
			ListNode temp1 = new ListNode(0);
			temp1.val = sum;
//			System.out.println(sum);
			l1.next = temp1;
			l3 = l1;
			l1 = l1.next;
			l2 = l2.next;
		}
		while (l1 != null) {
			int sum = l1.val + flag;
			if (sum>=10) {
				sum = sum - 10;
				flag = 1;
			}
			else {
				flag = 0;
			}
			l1.val = sum;
			l3 = l1;
			l1 = l1.next;
		}
		if (flag==1) {
			l1 = l3.next;
			ListNode temp1 = new ListNode(1);
			l1.next = temp1;
		}
		
		return ret;
	}
	
	public static void main(String args[]) {
		ListNode lsListNode = new ListNode(0);
		ListNode retListNode = lsListNode;
		lsListNode.val = 9;
		ListNode retListNode2 = new ListNode(0);
		retListNode2.val = 9;
		lsListNode.next = retListNode2;
//		ListNode retListNode3 = new ListNode(0);
//		retListNode3.val = 5;
//		retListNode2.next = retListNode3;
//		while (retListNode != null) {
//			System.out.println(retListNode.val);
//			retListNode = retListNode.next;
//		}
		ListNode retListNode3 = new ListNode(0);
		retListNode3.val = 1;
		ListNode ret = addTwoNumbers(retListNode3,retListNode);
		while(ret!=null){
			System.out.print(ret.val);
			ret = ret.next;
		}
		
		System.out.println("\nok");
		
	}
}